package jp.sinya;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

/**
 * 获取请求参数
 * ①getParameter(String) 获取知道那个名称的请求参数值，适用于单值的请求参数
 * ②getParameterValues(String) 获取指定名称的请求参数值，适用于多值
 * ③getParameterMap() 获取所有的请求参数， 以键值对的方式
 */
public class DemoServlet10 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setHeader("Content-Type", "text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<h3>GET请求成功</h3>");

        String param1 = req.getParameter("username");
        String param2 = req.getParameter("password");
        writer.write("<hp>param1 value: " + param1 + "</p>");
        writer.write("<hp>param1 value: " + param2 + "</p>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setHeader("Content-Type", "text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<h3>POST请求成功</h3>");

        String param1 = req.getParameter("username");
        String param2 = req.getParameter("password");
        String[] param3 = req.getParameterValues("hobby");
        writer.write("<hp>param1 value: " + param1 + "</p>");
        writer.write("<hp>param1 value: " + param2 + "</p>");
        writer.write("<hp>param3 value: " + Arrays.toString(param3) + "</p><br>");

        //获取所有请求参数的名称
        Enumeration params = req.getParameterNames();
        while (params.hasMoreElements()) {
            writer.write("<hp>param name: " + params.nextElement() + "</p>");
        }
        writer.write("<br/>");

        //把所有请求参数，封装到Map中
        Map<String, String[]> map = req.getParameterMap();
        for (String paramName : map.keySet()) {
            String[] values = map.get(paramName);
            writer.write("<hp>param name: " + paramName + "; value: " + Arrays.toString(values) + "</p>");
        }
    }
}
